package com.example.soss.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.soss.entity.Result;
import com.example.soss.entity.ResultEnum;
import com.example.soss.entity.Student;
import com.example.soss.mapper.StudentMapper;
import com.example.soss.util.JwtTokenUtil;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class StudentService {

    @Resource
    private StudentMapper studentMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHead}")
    private String tokenHead;


    private static Cache<String, Student> cacheStudent = CacheBuilder.newBuilder()
            .initialCapacity(4000)
            .expireAfterWrite(2, TimeUnit.HOURS).build();


    public Result login(Student student) {
        Student data = getStudentByUsername(student.getUsername());
        if (data == null) return Result.failure(ResultEnum.LOGIN_FAILURE);

        boolean matches = passwordEncoder.matches(student.getPassword(), data.getPassword());
        if (matches) {
            //验证成功
            String jwt = jwtTokenUtil.generateToken(student);
            String token = tokenHead + "-" + jwt;
            return Result.success(ResultEnum.LOGIN_SUCCESS, token);
        }
        return Result.failure(ResultEnum.LOGIN_FAILURE);
    }


    public Collection<? extends GrantedAuthority> getAuthorities(int id) {
        Student student = studentMapper.selectById(id);
        List<GrantedAuthority> list = new ArrayList<>();
        list.add(() -> {

            switch (student.getType()) {
                case 1:
                    return "admin";
                default:
                    return "student";
            }
        });
        return list;
    }


    public Student getStudentByUsername(String username) {
        Student student = cacheStudent.getIfPresent(username);
        if (student == null) {
            student = studentMapper.selectOne(new QueryWrapper<Student>().eq("username", username));
            if (student == null) {
                return null;
            }
            cacheStudent.put(username, student);
            log.info("从DB中获取用户信息");
            return student;
        }
        log.info("从缓存中获取用户信息");
        return student;
    }
}

